package wh.coach.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author hangwen
 * @date 2023/7/24
 */
public class FileUtils {

    public static void writeToFile(final File file, final boolean createFileIfNotExists, final byte[] data) throws IOException {
        if (createFileIfNotExists) {
            final File folder = file.getParentFile();
            if (folder != null) {
                folder.mkdirs();
            }

            file.createNewFile();
        }

        try (OutputStream outputStream = new FileOutputStream(file, false)) {
            outputStream.write(data);
        }
    }

    public static void writeToFile(File file, boolean createFileIfNotExists, InputStream inputStream) throws IOException {
        if (createFileIfNotExists) {
            final File folder = file.getParentFile();
            if (folder != null) {
                folder.mkdirs();
            }
            file.createNewFile();
        }

        try (OutputStream outputStream = new FileOutputStream(file, true)) {
            int bytesRead;
            byte[] buffer = new byte[1024];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);

            }

        }

    }
}
